package com.threegroup.web.interceptor;

import com.threegroup.common.exception.ErrorCode;
import com.threegroup.common.exception.TakeOutException;
import com.threegroup.web.annotation.Login;
import com.threegroup.web.entity.TokenEntity;
import com.threegroup.web.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 权限(Token)验证
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
@Slf4j

public class AuthorizationInterceptor implements HandlerInterceptor {
    @Resource
    private TokenService tokenService;

    public static final String USER_KEY = "userId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }

        if(annotation == null){
            return true;
        }

        //从header中获取token
        String token = request.getHeader("token");
        log.info("token={}",token);
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
            log.info("token={}",token);
        }

        //token为空
        if(StringUtils.isBlank(token)){
            throw new TakeOutException(ErrorCode.TOKEN_NOT_EMPTY);
        }

        //查询token信息
        TokenEntity tokenEntity = tokenService.getByToken(token);
        if(tokenEntity == null){
            throw new TakeOutException(ErrorCode.TOKEN_INVALID);
        }
        if (tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) {
            log.info("token 过期, 重新生成token");
            tokenService.createToken(tokenEntity.getUserId());
        }

        //设置userId到request里，后续根据userId，获取用户信息
        request.setAttribute(USER_KEY, tokenEntity.getUserId());
        log.info("userId={}",request.getAttribute("userId"));
        return true;
    }
}
